<template>
  <a-modal
    title="导入客户"
    :width="640"
    :visible="visible"
    @cancel="() => { visible = false }"
  >
    <template slot="footer">
      <a-button
        type="primary"
        :disabled="fileList.length === 0"
        :loading="uploading"
        @click="handleImport">
        导入
      </a-button>
      <a-button @click="visible = false">
        关闭
      </a-button>
    </template>
    <a-form v-bind="formLayout">
      <a-form-item label="模板上传">
        <a-upload
          accept=".xls,.xlsx"
          :file-list="fileList"
          :remove="handleRemove"
          :before-upload="beforeUpload">
          <a-button> <a-icon type="upload" /> 上传文件 </a-button>
          <span style="margin-left: 16px;color: #ccc;">请上传.xls、xlsx</span>
        </a-upload>
      </a-form-item>
      <a-form-item label="导入模板">
        <a href="">下载导入模板</a>
      </a-form-item>
      <span style="margin-left: 105px;color: #ccc;">说明：每次导入上限为3000条，导入大量数据的情况下，请分批导入</span>
    </a-form>
  </a-modal>
</template>

<script>
import { importUserTable } from '@/api/consumer'
export default {
  props: {
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      visible: false,
      model: null,
      fileList: [],
      uploading: false
    }
  },
  created () {
  },
  methods: {
    importView (record) {
      this.visible = true
      this.model = record
    },
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      const isXlS = file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      if (!isXlS) {
        this.$message.error('只能上传xls、xlsx格式的文件!')
      } else {
        this.fileList = [file]
      }
      return false
    },
    handleImport () {
      const { fileList } = this
      const formData = new FormData()
      fileList.forEach(file => {
        formData.append('files[]', file)
      })
      this.uploading = true

      importUserTable(formData).then(res => {
          this.uploading = false
          this.$message.success('导入成功')
      }).finally(() => {
          this.uploading = false
      })
    }
  }
}
</script>
